/*
 * Copyright 2008 Carnegie Mellon University
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, 
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

// variables

//depends on resources.js.jsp

var isLogInPage = typeof(contextPath) == "undefined";
if (isLogInPage) {contextPath = '/sepia';} 
var jsonPath = contextPath+"/json";
var topicId;
var lastTopicId = new Array();

/*******************************************************
 * Message display related functions
 *******************************************************/

function showMessage( msg ) {
  jQuery.notifyBar({
    html: msg,
    delay: 2500,
    close: true,
    cls: "success",
    animationSpeed: "normal"
  });
}

function showErrMessage( msg ) {
  jQuery.notifyBar({
    html: msg,
    delay: 2500,
    close: true,
    cls: "error",
    animationSpeed: "normal"
  });
}

/*******************************************************
 * Message Resource related functions
 *******************************************************/
function loadMessages( lang ) {
  //load message in span etc
  //Don't select input ... ie6 will fail.
  jQuery('h1[id^="msg_"],h2[id^="msg_"],h3[id^="msg_"],h4[id^="msg_"],div[id^="msg_"],span[id^="msg_"],strong[id^="msg_"],legend[id^="msg_"],a[id^="msg_"]').each(function(){
    var obj = jQuery(this);
    var message = msg( lang, obj.attr('id') );
    if (!!message) {
      obj.html( message );
    }
    message = msg( "EN", obj.attr('id') );
    if (!!message) {
      obj.attr( 'title', message );
    }
  });
  
  jQuery('input[class^="msg_"],input[id^="msg_"]').each(function(){
    var obj = jQuery(this);
    var message = msg( lang, obj.attr('id') );
    if (message) {
      obj.val( message );
    }
  });

  jQuery('input,select').each(function(){
    var obj = jQuery(this);
    var message = msg( lang, "msg_"+obj.attr('id')+"_help" );
    if (message) {
      obj.attr('title', message); 
    }
  });
}

/*******************************************************
 * Session out/invalid access detection
 *******************************************************/

//Session checker
var sessionOutDetected = 0;
function detectSession() {
  if (!isLogInPage && !sessionOutDetected) {
    var json = syncInternal( contextPath+"/js/sessionInfo.jsp", {} );
    if ( json.isSessionLost ) {
      sessionOutDetected = 1;
      var goHome = window.confirm("Session lost: please log in again.");
      if ( goHome ) {
        top.location.href = contextPath+"/auth/logout.jsp";
      }
    }
  }
}
var timer = setInterval("detectSession()",30000);

/*******************************************************
 * Header
 *******************************************************/

function loadHeaderTop( lang ) {
  loadHeader( lang, 0 );
}

function loadHeaderSub( lang ) {
  loadHeader( lang, 1 );
}

function loadHeaderSubSub() {
  loadHeader( lang, 2 );
}

function loadHeader( lang, depth ) {
  var newdiv = document.createElement("div");
  
  //var status = msg(lang, "msg_loggedin").replace("@USERNAME@", userName).replace("@TASKNAME@", taskName).replace("@LANG@", lang);
  var status = msg(lang, "msg_loggedin").replace("@USERNAME@", userName).replace("@LANG@", lang);
  if ( window.taskName!=null ) {
    var name = "ADMIN";
    if ( srcLang==trgLang || !srcLang ) {
      if (trgLang) {
        name = taskName+" ("+trgLang+")";
      } else {
        name = taskName+" N/A";
      }
    } else {
      name = taskName+" ("+srcLang+"-"+trgLang+")";
    }
    status = status.replace("@TASKNAME@", name);
  }
    var home = '';
    if (depth>=1) {
      home += '<input id="msg_home" type="button" onclick="top.location.href=\''+contextPath+'/\'" style="width:80px" value="'+msg(lang, "msg_home")+'">';
    }
    if (depth>=2) {
      home += '&nbsp;&nbsp;&gt;&nbsp;&nbsp;<input id="msg_task_home" type="button" onclick="top.location.href=\''+contextPath+'/task_menu.jsp\'" style="width:100px" value="'+msg(lang, "msg_task_home")+'">';
    }
      
  newdiv.innerHTML = [  
  '<table width="100%" cellpadding="0" cellspacing="0" border="0"><tr>',
  '<td><span id="top"></span>',
  home,
  '</td><td align="right">',
  status,
  '&nbsp;&nbsp;',
  '<input id="msg_logout" type="button" onclick="top.location.href=\''+contextPath+'/auth/logout.jsp\'" style="width:80px" value="Logout">',
  '</td></tr></table>',
  '<hr size=1>'
  ].join('');
  
  if ( $('header_content') ) {
    $('header').removeChild($('header_content'));
  }
  newdiv.id = 'header_content';
  $('header').appendChild(newdiv);
}



/*******************************************************
 * Footer
 *******************************************************/

jQuery.fn.bottom = function() {
  var scrollHeight = jQuery(document).height();
  var scrollPosition = jQuery(window).height() + jQuery(window).scrollTop();
  var threshold = 0.01;
  
  if ((scrollHeight - scrollPosition) / scrollHeight <= threshold) {
    this.fadeIn('slow').css("top", (scrollHeight-55)+"px").css("right", "0px");
  } else {
    this.fadeOut('slow');
  }
  return this;
};

var footer = function() {
  jQuery("#footer").bottom();
};

jQuery(document).ready( function() {
  jQuery('body').append('<br><br><br>');
  
  jQuery('#footer')
    .attr( 'align', 'right' )
    .css( 'color', '#ccc' )
    .css( 'width', '100%' )
    .css( 'position', 'absolute' )
    .css( 'z-index', '100' )
    .css( 'display', 'none' )
    .css( 'padding', '8px' );
  var newdiv = document.createElement("div");
  newdiv.innerHTML = [
  '<hr size="1">',
  'Powered by <a href="https://mu.lti.cs.cmu.edu/trac/sepia" target="_blank" style="color:#ccc;font-weight:bold">SEPIA '+sepiaVersion+'</a>'
  ].join("");
  if (jQuery('#footer').length>0) {
    jQuery('#footer')[0].appendChild(newdiv);
  }
  
  // wait until elements drawn
  setTimeout( footer, 2000);
});

jQuery(window).bind('resize scroll', footer);


/*******************************************************
 * Json
 *******************************************************/

/**
 * Synchronous version of AJAX!
 * @param param
 * @return json object
 */
function sync( param ) {
  return syncInternal( jsonPath, param );
}

function syncInternal( path, param ) {
  var request = new Ajax.Request( path, {
        method: "post",
        asynchronous: false,
        parameters: param, 
        onFailure: function(request) {   
            showErrMessage("[ERROR] "+msg_failed);
        },   
        onException: function (request,exception) {
            showErrMessage("[EXCEPTION] "+msg_error+" "+exception);  
        }   
    } );
  // TODO: if response include 404, it measn server is down/missing
  return eval("(" + request.transport.responseText + ")");
}

function initSelect( selectObj ) {
  selectObj.innerHTML = '';
  var opt = document.createElement("option");
  selectObj.appendChild( opt );
}

// criteria of done is different depending on the tool.
function loadTopicList( tool ) {
  var tl = $('topicList');
  initSelect(tl);

  var param = eval('$H({"action":"GetTopics", "tool": "' + tool + '"})').toQueryString();
  var json = sync(param);
  if (json.topics.length>0) {
    jQuery('#select_a_task').slideDown("slow",footer);
  }
  for (var i = 0; i < json.topics.length; i++) {
    var t = json.topics[i];
    var done = ( (tool!="nv" && t.done==1) || (tool=="nv" && t.done>0) )?done_prefix:"";
    var prefix = t.externalId?(t.externalId+': '):'';
    var opt = document.createElement("option");
    opt.value = t.topicId;
    opt.id = "topicList"+t.topicId;
    opt.innerHTML = done+prefix+t.title;
    tl.appendChild( opt );
  }
  if ( json.topics.length==0 ) { 
    tl.style.width = '160px';
    tl.disable();
  }
  
  //select
  if ( lastTopicId[tool] != null && $("topicList"+lastTopicId[tool]) != null ) {
    $("topicList"+lastTopicId[tool]).selected = true;
  }
}

/** Postprocess: escaping special characters. **/
function es( str ) {
  //new String(str) needed for chrome
  return new String(str).replace(/\'/g, '&apos;').replace(/\"/g, '\\\"');
}

/** Postprocess: unescaping special characters. **/
function ues( str ) {
  return new String(str).replace(/&apos;/g, '\'').replace(/\"/g, '\"');
}

function cleanup( obj ) {
  return obj.value = obj.value.replace(/(\r)?\n/g,'');
}

/*******************************************************
 * Data Table
 *******************************************************/
//using prototype function
function zebraBG() {
  var tables = document.getElementsByTagName('table');
    for (var i=0;i<tables.length;i++) {
    if ( Element.classNames(tables[i])=="datatable" ) {
      var trs = tables[i].getElementsByTagName('tr');
      for (var j=0;j<trs.length;j++) {
        if ( trs[j].getElementsByTagName('td').length>0 ) {
          Element.addClassName(trs[j],(j%2==1?"odd":"even"));
        }
      }
    }
  }  
}

function printRotatedText(text){
//  var tex = '\\tiny{\\text{\\rotatebox{90}{'+text+'}}}';
 var tex = '\\tiny{\\text{\\rotatebox{90}{'+text+'}}}';
 var u = 'http://chart.apis.google.com/chart?cht=tx&chl='
 + encodeURIComponent(tex);
 document.writeln("<img src='"+u+"'>");
}

//////////////////////////////////////////
//////////////////////////////////////////
//////////////////////////////////////////

/**
 * Used by NE and NV, and ir eval
 */
function loadTopicJsonIntoHTML(json) {
  loadTopicIntoHTML( json.topics[0] );
}

function loadTopicIntoHTML(topic) {
  if ( $('topicId') ) $('topicId').value = topic.topicId;
  if ( $('externalId') ) $('externalId').value = ues( topic.externalId );
  if ( $('questionSrc') )  $('questionSrc').innerHTML = ues( topic.questionSrc );
  if ( $('questionTrg') )  $('questionTrg').innerHTML = ues( topic.questionTrg );
  if ( $('narrativeSrc') ) $('narrativeSrc').innerHTML = ues( topic.narrativeSrc );
  if ( $('narrativeTrg') ) $('narrativeTrg').innerHTML = ues( topic.narrativeTrg );
  if ( $('note') ) $('note').innerHTML = ues( topic.note );
  if ( $('type') ) $('type').innerHTML = topic.type;
}

function updateDone( tool ) {
  var done;
  var topic = $('topicList').options[$('topicList').selectedIndex].innerHTML;
  if ( ($('done')!=null && $('done').checked) || tool == "nv" ) {
    done = 1;
    topic = done_prefix+topic;
    log("DONE","tool="+tool+", topic id="+$('topicId').value);
  } else {
    done = 0;
    topic = topic.replace(done_prefix, "");
    log("UNDONE","tool="+tool+", topic id="+$('topicId').value);
  }
  var param = [];
  param.action  = "UpdateProgress";
  param.tool    = tool;
  param.topicId = $('topicId').value;
  param.userId  = userId;
  param.isDone  = done;
  sync(param);
  loadTopicList( tool );
  
  showMessage( msg_done_task );
}

function log( logEvent, detail ) {
  var param = eval('$H({"action":"AddLog","logEvent": "'+logEvent+'", "detail": "'+escape(detail)+'" })').toQueryString();
  sync(param);
}

function deleteConfirmed() {
  return window.confirm("Do you really want to delete? This process cannot be undone.");
}

//initialize list
function initList( list ) {
  list.disabled=true;
  list.innerHTML = '';
   var opt0 = document.createElement("option");
   opt0.value = '';
   list.appendChild( opt0 );
   var opt = document.createElement("option");
   var str = document.createTextNode("Loading ...");
   opt.appendChild(str);
   opt.selected = true;
   list.appendChild( opt );
}
function resetList( list ) {
  list.innerHTML = '';
  var opt0 = document.createElement("option");
  opt0.value = '';
  list.appendChild( opt0 );
  list.disabled=false;
}

/*******************************************************
 * Form
 *******************************************************/
function checkAll(className) {
  for(var i=0;i<document.getElementsByClassName(className).length;i++){
    document.getElementsByClassName(className)[i].checked=true;
  }
}
function uncheckAll(className) {
  for(var i=0;i<document.getElementsByClassName(className).length;i++){
    document.getElementsByClassName(className)[i].checked=false;
  }
}
function verifyChecked(className) {
  var flag = 0;
  for(var i=0;i<document.getElementsByClassName(className).length;i++){
    if ( document.getElementsByClassName(className)[i].checked ) {
      flag = 1;
    }
  }
  return flag;
}

function verifyAlphanumeric(formObj) {
  var dbName = formObj.value;
  // make it a boolean
  var passed = !!dbName.match(/^[a-zA-Z0-9_]+$/);
  if (!passed) {
    alert('You cannot use characters other than alphabets, numbers, and underscores.');
    formObj.focus();
    formObj.select();
  }
  return passed;
}

function verifyNonBlank(formObj) {
  var dbName = formObj.value;
  // make it a boolean
  var passed = dbName.length>0;
  if (!passed) {
    var name = '';
    if (!!formObj.name) {name = formObj.name+' ';} 
    alert('You cannot keep the filed '+name+'blank.');
    formObj.focus();
    formObj.select();
  }
  return passed;
}

/*******************************************************
 * Text Util
 *******************************************************/

function getSelectedText() {
  var w=window,d=w.document,s="";
  if (d.selection) {
   s = d.selection.createRange().text;
  } else if (d.getSelection) {
    s = d.getSelection();
  } else if (w.getSelection) {
    s = w.getSelection();
  }
  return s;
}

/*******************************************************
 * Cookie Util
 *******************************************************/

function getCookie(key) {
  var tmp1 = " " + document.cookie + ";";
  var xx1 = 0;
  var xx2 = 0;
  var len = tmp1.length;
  while (xx1 < len) {
    xx2 = tmp1.indexOf(";", xx1);
    var tmp2 = tmp1.substring(xx1 + 1, xx2);
    var xx3 = tmp2.indexOf("=");
    if (tmp2.substring(0, xx3) == key) {
      return (unescape(tmp2.substring(xx3 + 1, xx2 - xx1 - 1)));
    }
    xx1 = xx2 + 1;
  }
  return("");
}

function setCookie(key, val) {
  var cookieValue = key + "=" + escape(val) + "; " + 
  "expires=Fri, 31-Dec-2030 23:59:59; ";
  document.cookie = cookieValue;
}

function clearCookie(key) {
  document.cookie = key + "=xx; expires=1-Jan-1997 00:00:00;";
}


/**
 * Select/deselect any matching checkboxes, radio buttons or option elements.
 * http://forum.jquery.com/topic/cannot-set-selected-selected-via-attr-on-option-elements
 */
jQuery.fn.selected = function(select) {
  if (select == undefined) select = true;
  return this.each(function() {
    var t = this.type;
    if (t == 'checkbox' || t == 'radio')
      this.checked = select;
    else if (this.tagName.toLowerCase() == 'option') {
      var $sel = jQuery(this).parent('select');
      if (select && $sel[0] && $sel[0].type == 'select-one') {
        // deselect all other options
        $sel.find('option').selected(false);
      }
      this.selected = select;
    }
  });
};

/****************** from jquery.notifyBar.js ************************/

/*
* Notify Bar - jQuery plugin
*
* Copyright (c) 2009-2010 Dmitri Smirnov
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*
* Version: 1.2.2
*
* Project home:
* http://www.dmitri.me/blog/notify-bar
*/
 
/**
* param Object
*/
jQuery.notifyBar = function(settings) {
  
  (function($) {
    
    var bar = notifyBarNS = {};
    notifyBarNS.shown = false;
     
    if( !settings) {
    settings = {};
    }
    // HTML inside bar
    notifyBarNS.html = settings.html || "Your message here";
     
    //How long bar will be delayed, doesn't count animation time.
    notifyBarNS.delay = settings.delay || 2000;
     
    //How long notifyBarNS bar will be slided up and down
    notifyBarNS.animationSpeed = settings.animationSpeed || 200;
     
    //Use own jquery object usually DIV, or use default
    notifyBarNS.jqObject = settings.jqObject;
     
    //Set up own class
    notifyBarNS.cls = settings.cls || "";
    
    //close button
    notifyBarNS.close = settings.close || false;
    
    if( notifyBarNS.jqObject) {
      bar = notifyBarNS.jqObject;
      notifyBarNS.html = bar.html();
    } else {
      bar = jQuery("<div></div>")
      .addClass("jquery-notify-bar")
      .addClass(notifyBarNS.cls)
      .attr("id", "__notifyBar");
    }
         
    bar.html(notifyBarNS.html).hide();
    var id = bar.attr("id");
    switch (notifyBarNS.animationSpeed) {
      case "slow":
      asTime = 600;
      break;
      case "normal":
      asTime = 400;
      break;
      case "fast":
      asTime = 200;
      break;
      default:
      asTime = notifyBarNS.animationSpeed;
    }
    if( bar != 'object'); {
      jQuery("body").prepend(bar);
    }
    
    // Style close button in CSS file
    if( notifyBarNS.close) {
      bar.append('<a href="#" class="notify-bar-close">Close [X]</a>');
      jQuery(".notify-bar-close").click(function() {
        if( bar.attr("id") == "__notifyBar") {
          jQuery("#" + id).slideUp(asTime, function() { jQuery("#" + id).remove(); });
        } else {
          jQuery("#" + id).slideUp(asTime);
        }
        return false;
      });
    }
    
    bar.slideDown(asTime);
     
    // If taken from DOM dot not remove just hide
    if( bar.attr("id") == "__notifyBar") {
      setTimeout("jQuery('#" + id + "').slideUp(" + asTime +", function() {jQuery('#" + id + "').remove()});", notifyBarNS.delay + asTime);
    } else {
      setTimeout("jQuery('#" + id + "').slideUp(" + asTime +", function() {jQuery('#" + id + "')});", notifyBarNS.delay + asTime);
    }

})(jQuery); };